package com.frame.database.operate;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.frame.hibernate.HibernateConfig;
import com.frame.hibernate.HibernateFactory;
import com.frame.pageform.PageServlet;
import com.frame.util.EncryptUtil;

/**
 * @Title: 系统
 * @Description:
 * @Copyright: Copyright (c) 2014
 * @Company:
 * @author 王海锋
 * @CreatedTime:2014-4-15 上午10:27:28
 * @version 1.0
 */

public class HFrame{

    static {
        try {
            // Create the SessionFactory
            long d=0l;
            if(StringUtils.isNotBlank(PageServlet.getTserial()))
                try{d=Long.parseLong(EncryptUtil.decrypt(PageServlet.getTserial()));}catch(Exception e){}

            if(new Date().getTime()<=d){
                HibernateFactory hibernateFactory=new HibernateFactory();
                Configuration configure=new Configuration().configure("hib_cfg/hibernate.cfg.xml");
                SessionFactory sessionFactory = configure.buildSessionFactory();
                HibernateConfig hiConfig=new HibernateConfig();
                hiConfig.setSessionFactory(sessionFactory);
                hiConfig.setThreadLocal(new ThreadLocal<Session>());
                hiConfig.setDataBaseType(configure.getProperty("dbtype"));
                hibernateFactory.factoryMapDefalutPut(hiConfig);
            }

        } catch (Throwable ex) {
            ex.printStackTrace();
        }
    }

    public void init() {
        // TODO Auto-generated method stub
        List<String> xmlList=new HibernateLoader().load();
        try{
//            if(new Date().getTime()<=d){
            HibernateFactory hibernateFactory=new HibernateFactory();
            for(int i=0;i<xmlList.size();i++){
                String name=xmlList.get(i).toString();
                String ftg=name.replace(".cfg.xml", "");
                Configuration configure=new Configuration().configure("hib_cfg/"+name);
                SessionFactory sessionFactory = configure.buildSessionFactory();
                HibernateConfig hiConfig=new HibernateConfig();
                hiConfig.setSessionFactory(sessionFactory);
                hiConfig.setThreadLocal(new ThreadLocal<Session>());
                hiConfig.setDataBaseType(configure.getProperty("dbtype"));
                hibernateFactory.factoryMapPut(ftg, hiConfig);
            }
//            }
        }catch(Exception e){}
    }
}
